#pragma once
#include "../comm/util.hpp"
#include "../comm/log.hpp"

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <cstdlib>
#include <cassert>

namespace ns_model
{
    using namespace std;
    using namespace ns_log;

    struct Question
    {
        std::string number; // 题目编号
        std::string title;  // 题目标题
        std::string star;   // 题目难度：简单 中等 困难
        int cpu_limit;
        int mem_limit;
        std::string desc;
        std::string header;
        std::string tail;
    };

    const std::string questions_list = "./questions/questions.list";
    const std::string questions_path = "./questions/";
    class Model
    {
    private:
        // <题号,题目细节(编号，标题，难度，时间限制，内存限制，描述)>
        unordered_map<string, Question> questions;

    public:
        Model()
        {
            assert(LoadQuestionList(questions_list));
        }
        bool LoadQuestionList(const std::string &question_list)
        {
            ifstream in(question_list);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载题库失败,请检查是否存在题库文件" << "\n";
                return false;
            }
            string line;
            // 逐行读取，并切割 填充
            while (getline(in, line))
            {
                vector<string> tokens;
                StringUtil::SplitString(line, &tokens, " ");
                if (tokens.size() != 5)
                {
                    LOG(WARING) << "加载部分题目失败，请检查文件格式" << "\n";
                }
                Question q;
                q.number = tokens[0];
                q.title = tokens[1];
                q.star = tokens[2];
                q.cpu_limit = atoi(tokens[3].c_str());
                q.mem_limit = atoi(tokens[4].c_str());
                string path = questins_path;
                path += q.number;
                path += "/";

                FileUtil::ReadFile(path + "desc.txt", &(q.desc), true);
                FileUtil::ReadFile(path + "header.txt", &(q.header), true);
                FileUtil::ReadFile(path + "tail.txt", &(q.tail), true);
                questions.insert({q.number, q});
            }
            LOG(INFO) << "加载题库..成功！" << "\n";
            in.close();

            return true;
        }
        bool GetAllQuestions(vector<Question> *out)
        {
            if (questions.size() == 0)
            {
                return false;
            }
            for (const auto &q : questions)
            {
                out->push_back(q.second);
            }
            return true;
        }
        bool GetOneQuestion(const std::string &number, Question *q)
        {
            const auto &iter = questions.find(number);
            if (iter == questions.end())
            {
                return false;
            }
            (*q) = iter->second;
            return true;
        }
        ~Model()
        {
        }
    };
}